package com.bilibili.juc.LockSupportTest;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//await和notify类似于上面wait和notify
// Condition中的线程等待和唤醒方法，需要先获取锁
// 一定要先await后signal，不能反了

//Object和Condition使用的限制条件
// 总结
// 线程先要获得并持有锁，必须在锁块（synchronized或lock）中
// 必须要先等待后唤醒，线程才能够被唤醒
/**
 * @author 小泽
 * @create 2022-09-21  10:32
 * 记得每天敲代码哦
 */
public class LockSupportDemo2 {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t-----come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "\t -----被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        //暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            lock.lock();
            try {
                condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + "我要进行唤醒");
        }, "t2").start();

    }
}
//t1  -----come in
//t2  我要进行唤醒
//t1   -----被唤醒
